import React, { useEffect, useState } from "react";
import  "./index.less";
import MyTabbar from "@/components/MyTabbar";
import axios from '@/utils/request'
import { useNavigate } from "umi";

export default function Page() {
  const navigate = useNavigate();
  const [cates, setCates] = useState<CateType[]>([]);
  const [items, setItems] = useState<ItemType[]>([]);
  const [activeIndex, setActiveIndex] = useState(0);
  // 请求所有分类
  const getCates  = () => {
    axios.get('/shop/goods/category/all').then(res => {
      if (res.data.code === 0) {
        setCates(res.data.data);
      }
    })
  }
  // 请求高亮分类下的商品列表
  const getItems = () => {
    axios.post('/shop/goods/list/v2', {
      categoryId: cates[activeIndex].id
    }).then(res => {
      if (res.data.code === 0) {
        setItems(res.data.data.result)
      }
      if (res.data.code === 700) {
        setItems([])
      }
    })
  }
  // 点击切换高亮分类
  const switchActiveCate  = (index: number) => {
    setActiveIndex(index)
  }
  useEffect(() => {
    if (cates.length) {
      getItems();
    }
    
  }, [cates, activeIndex])
  useEffect(() => {
    getCates()
  }, [])
  // 跳转到详情
  const enterDetail = (id: number) => {
    navigate(`/detail/${id}`)
  }
  return (
    <>
      <div className="cate-page">
        <div className="cate-container">
          {
            cates.map((cate:CateType, index: number) => (
              <div 
                key={cate.id}
                onClick={
                  () => {
                    switchActiveCate(index)
                  }
                }
                className={`cate ${activeIndex === index?'active': ''}`}>
                  {cate.name}
                </div>
            ))
          }
         
        </div>
        <div className="item-container">
        <div className="items">
          {items.map((item: ItemType) => (
            <div className="item" onClick={
              () => {
                enterDetail(item.id)
              }
            } key={item.id}>
              <img src={item.pic} alt="" className="item-img" />
              <div className="item-info">
                <h5>{item.name}</h5>
                <p className="price">{item.minPrice}</p>
              </div>
            </div>
          ))}
        </div>
        </div>
      </div>
      <MyTabbar />
    </>
  );
}
